import React, { ReactNode, useState } from 'react';
import styled from 'styled-components';
import dayjs from 'dayjs';
import EChartsReact from 'echarts-for-react';
import { CategorySection } from 'views/Money/CategorySection';
import { RecordItem, useRecords } from 'hooks/useRecords';
import { useTags } from 'hooks/useTags';
import { Layout } from 'components/Layout';
import { Empty } from 'components/Empty';
import { StatisticWrapper } from './StatisticWrapper';
import { getEchartConfig } from './generateEchartConfig';

const CategoryWrapper = styled.div`
  background: #fff;
`;

export default function Statistic() {
  const [category, setCategory] = useState<'-' | '+'>('-');
  const { records } = useRecords();
  const { getName } = useTags();
  const hash: { [key: string]: RecordItem[] } = {};
  const selectedRecords = records.filter(r => r.category === category);

  selectedRecords.forEach(r => {
    const key = dayjs(r.createdAt).format('YYYY-MM-DD');
    const value = r;
    if (!(key in hash)) {
      hash[key] = [];
    }
    hash[key].push(value);
  });

  const array = Object.entries(hash).sort((a, b) => {
    if (a[0] === b[0]) return 0;
    if (a[0] > b[0]) return -1;
    if (a[0] < b[0]) return 1;
    return 0;
  });

  const generateChartData = () => {
    const xData: string[] = [];
    const yData: number[] = [];
    if (array.length !== 0) {
      array.forEach(item => {
        xData.unshift(item[0]);
        yData.unshift(
          item[1].reduce((result, item) => result + item.amount, 0)
        );
      });
    }
    return { xData, yData };
  };

  return (
    <Layout>
      <CategoryWrapper>
        <CategorySection
          value={category}
          onChange={value => setCategory(value)}
        />
      </CategoryWrapper>

      {array.length !== 0 && (
        <EChartsReact
          option={getEchartConfig(generateChartData())}
          style={{ width: '100%', height: '160px' }}
        />
      )}

      {array.length === 0 ? (
        <Empty />
      ) : (
        <StatisticWrapper>
          {array.map(([date, records]) => (
            <div className="container" key={date}>
              <div className="date-section">
                <h3>{date}</h3>
                <span className="amount">
                  ￥{records.reduce((result, item) => result + item.amount, 0)}
                </span>
              </div>
              <div className="record-section">
                {records.map(r => {
                  return (
                    <div className="record-item" key={r.createdAt}>
                      <div className="tags">
                        {r.tagIds
                          .map(tagId => (
                            <span key={tagId}>{getName(tagId)}</span>
                          ))
                          .reduce(
                            (result, span, index, array) =>
                              result.concat(
                                index < array.length - 1 ? [span, ','] : [span]
                              ),
                            [] as ReactNode[]
                          )}
                      </div>
                      {r.note && <div className="note">{r.note}</div>}
                      <div className="amount">￥{r.amount}</div>
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </StatisticWrapper>
      )}
    </Layout>
  );
}
